package com.fiberhome.nas.feature.main.viewmodel

import com.fiberhome.nas.core.common.base.viewmodel.BaseNetWorkViewModel
import com.fiberhome.nas.core.data.repository.AlbumRepository
import com.fiberhome.nas.core.data.state.AppState
import com.fiberhome.nas.core.model.entity.AlbumInfo
import com.fiberhome.nas.core.model.response.ListData
import com.fiberhome.nas.core.model.response.NetworkResponse
import com.fiberhome.nas.core.network.di.NetworkManager
import com.fiberhome.nas.navigation.AppNavigator
import com.fiberhome.nas.navigation.routes.AlbumRoutes
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class AlbumViewModel @Inject constructor(
    navigator: AppNavigator,
    appState: AppState,
    private val albumRepository: AlbumRepository,
    private val networkManager: NetworkManager,
) : BaseNetWorkViewModel<ListData<AlbumInfo>>(navigator, appState) {

    private val _albums = MutableStateFlow<List<AlbumInfo>>(emptyList())
    val albums: StateFlow<List<AlbumInfo>> = _albums.asStateFlow()

    init {
        super.executeRequest()
    }

    override fun requestApiFlow(): Flow<NetworkResponse<ListData<AlbumInfo>>> {
        return albumRepository.getAlbumList()
    }

    override fun onRequestSuccess(data: ListData<AlbumInfo>) {
        _albums.value = data.items.sortedBy { it.id.toInt() }
        super.onRequestSuccess(data)
    }

    /**
     * 点击相册
     */
    fun onAlbumClick(albumItem: AlbumInfo) {
        super.toPage("$AlbumRoutes.DETAIL/${albumItem}")
    }

    /**
     * 获取相册封面
     */
    fun getAlbumThumbUrl(id: String): String {
        return "${networkManager.baseUrl}/api/v1/tscss/assets/${id}/thumbnail"
    }
}